package com.codedancer.campus.client.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.codedancer.campus.client.service.IUpdateLogService;
import com.codedancer.campus.client.service.vo.updateLog.UpdateLogVo;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.common.utils.UUIDGenerator;
import com.codedancer.campus.mapper.UpdateLogMapper;
import com.codedancer.campus.mapper.UpdateLogReadRecordMapper;
import com.codedancer.campus.po.UpdateLog;
import com.codedancer.campus.po.UpdateLogReadRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UpdateLogServiceImpl implements IUpdateLogService {

    @Autowired
    private UpdateLogMapper updateLogMapper;
    @Autowired
    private UpdateLogReadRecordMapper updateLogReadRecordMapper;

    /**
     * 获取最新的更新日志
     *
     * @return
     */
    @Override
    public UpdateLogVo latest(String currentLoginUserUuid) {
        // 获取置顶并且已推送的更新日志
        UpdateLog updateLog = updateLogMapper.getTopAndPushed();
        if (ObjectUtil.isEmpty(updateLog)) {
            return new UpdateLogVo();
        }
        // 判断是否已读最新更新日志
        if (updateLogReadRecordMapper.isRead(currentLoginUserUuid, updateLog.getUuid())) {
            return new UpdateLogVo();
        }
        UpdateLogVo updateLogVo = BeanUtil.copyProperties(updateLog, UpdateLogVo.class);
        updateLogVo.setContents(JSONUtil.toList(updateLog.getContent(), String.class));
        updateLogVo.setIsRead(false);
        return updateLogVo;
    }

    /**
     * 已读最新更新日志
     *
     * @param uuid
     */
    @Override
    public void read(String currentLoginUuid, String uuid) {
        UpdateLog updateLog = updateLogMapper.findById(uuid)
            .orElseThrow(() -> new BusinessException("更新日志不存在"));
        if (!updateLog.getIsTop()) {
            throw new BusinessException("更新日志不是最新");
        }
        if (updateLogReadRecordMapper.isRead(currentLoginUuid, uuid)) {
            throw new BusinessException("更新日志已阅读");
        }
        UpdateLogReadRecord updateLogReadRecord = UpdateLogReadRecord.builder()
            .uuid(UUIDGenerator.getUUID())
            .updateLogUuid(uuid)
            .userUuid(currentLoginUuid).build();
        updateLogReadRecordMapper.insert(updateLogReadRecord);
    }
}
